package 栈和队列;

import java.util.EmptyStackException;

public class ArrayStack {
    //
    private int base = -1;
    private int top = -1;
    private int capacity = 1;
    private int[] array;

    public static ArrayStack initStack(Object[] arr) {
        ArrayStack stack = new ArrayStack();
        for (Object o : arr) {
            stack.push((int) o);
        }
        return stack;
    }

    public ArrayStack() {
        array = new int[capacity];
    }

    public void push(int data) {
        if (base == -1) {
            base++;
            top++;
            array[base] = data;
        } else {
            if (isFullStack()) {
                doubleStack();
            }
            array[++top] = data;

        }
    }

    private void doubleStack() {
        int newArray[] = new int[capacity * 2];
        System.arraycopy(array, 0, newArray, 0, array.length);
        capacity = capacity * 2;
        array = newArray;
    }

    public int top() {
        if (isEmpty()) {
            throw new EmptyStackException();
        } else {
            return array[top];
        }
    }

    public int pop() {
        if (isEmpty()) {
            throw new EmptyStackException();
        } else {
            return array[--top];
        }
    }

    public boolean isEmpty() {
        return top == base;
    }

    public void deleteStack() {
        top = -1;
    }

    public boolean isFullStack() {
        return top == capacity - 1;
    }

    static class Main {
        public static void main(String[] args) {
            Object[] a = {1, 3, 4, 5, 9};
            ArrayStack stack = ArrayStack.initStack(a);
            System.out.println(stack.top());
        }
    }
}
